﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using Google.Protobuf.WellKnownTypes;
using log4net;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Cmp;
using Org.BouncyCastle.Asn1.X500;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
using static CloudApiServer.Controllers.DemoController;
using static log4net.Appender.RollingFileAppender;

namespace CloudApiServer.Controllers
{
    /// <summary>
    /// Home controller.
    /// </summary>
    [RoutePrefix("socialopen-sdbz")]
    public class FsiApiShandongBinZhouController : ApiController
    {
        /// <summary>
        /// 山东滨州医保接口控制器
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("api/stock")]
        [HttpPost]
        public async Task<IHttpActionResult>  stock (HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateShandongBinzhouApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    Console.WriteLine($"滨州医保完整传入：{request.Content.ReadAsStringAsync().Result}");
                    var BinzhouHeader = JsonConvert.DeserializeObject<FsiBinZhouHeader>(request.Content.ReadAsStringAsync().Result);
                    string mothod = BinzhouHeader.method.ToString();
                    string appid = BinzhouHeader.appid.ToString();
                    string bizContent = BinzhouHeader.bizContent.ToString();
                    Console.WriteLine($"滨州医保bizContent传入：{bizContent}");
                    if (string.IsNullOrEmpty(mothod) || string.IsNullOrEmpty(appid) || string.IsNullOrEmpty(bizContent))
                    {
                        throw new Exception($"接口类型mothod或Appid或bizcontent为空！请检查！当前入参：{request.Content.ReadAsStringAsync().Result}");
                    }
                    string returninfo = "";
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                    switch (mothod)
                    {
                        //国家接口转发的 调用山东进销存内部服务，几个接口入参均一致
                        case "social.trade.monitor":
                            var fsiRequestinfo = JsonConvert.DeserializeObject<FsiBinzhouRequestHeader<BinzhouInputSignIn>>(bizContent);
                            string info = fsiRequestinfo.info;
                            string fixmedins_code = fsiRequestinfo.fixmedins_code;
                            string fixmedins_name = fsiRequestinfo.fixmedins_name;
                            bool apitype;
                            string mader = PublicMethod.ApiPost(out apitype, $"{SystemInfo.localurl}:{SystemInfo.localurlpost}/hsu/mihs/MihsServlet", bizContent);
                            if (apitype==false)
                            {
                                throw new Exception($"调用山东进销存内部服务失败！错误内容：{mader}");
                            }
                            else
                            {
                                var FsiBinZhouRequest = new FsiBinZhouRequest
                                {
                                    code = 0,
                                    msg = "成功",
                                    bizContent = mader
                                };
                                return Json(FsiBinZhouRequest);
                            }
                        //订单推送
                        case "submit.social.trade.order":
                            int flag = 2;//订单传输标志
                            try
                            {
                                var order = JsonConvert.DeserializeObject<BinzhouOrder>(bizContent);
                                List<BinzhouOrderdetailList> list = new List<BinzhouOrderdetailList>();
                                list = order.details;
                                if (list == null)
                                {
                                    flag = 2;
                                    throw new Exception("参数校验失败：传入的订单商品列表为空");
                                }
                                await conn.OpenAsync();
                                using (MySqlTransaction transaction = conn.BeginTransaction())
                                {
                                    using (MySqlCommand cmd = conn.CreateCommand())
                                    {
                                        string psn_name = "";
                                        string cert_no = "";
                                        string insuplc_admdvs = "";

                                        cmd.CommandText = "select * from fsi_binzhou_order where tradeNo=@tradeNo and appid=@appid ";
                                        cmd.Parameters.AddWithValue("@tradeNo", order.tradeNo);
                                        cmd.Parameters.AddWithValue("@appid", appid);
                                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                                        {
                                            DataTable dt = new DataTable();
                                            dt.Load(reader);
                                            if (dt.Rows.Count >= 1)
                                            {
                                                flag = 1;
                                                throw new Exception($"查询订单表数据失败：传入的预订单编号tradeNo:{order.tradeNo}和Appid:{appid}已经存在！不允许再新增。");
                                            }
                                        }
                                        cmd.CommandText = "select * from fsi_PsnInfo where certno=@certno";
                                        cmd.Parameters.AddWithValue("@certno", FsiDatainfo.Defautlcardno);
                                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                                        {
                                            DataTable dt = new DataTable();
                                            dt.Load(reader);
                                            if (dt.Rows.Count == 1)
                                            {
                                                psn_name = dt.Rows[0]["psn_name"].ToString();
                                                cert_no = dt.Rows[0]["cert_no"].ToString();
                                                insuplc_admdvs = dt.Rows[0]["insuplc_admdvs"].ToString();
                                            }
                                            else
                                            {
                                                throw new Exception($"查询身份信息表数据失败：根据传入的人员证件号码【{FsiDatainfo.Defautlcardno}】查询到的人员信息总数为：{dt.Rows.Count}");
                                            }
                                        }
                                        cmd.Parameters.Clear();
                                        cmd.Transaction = transaction;
                                        try
                                        {
                                            cmd.CommandText = "INSERT INTO fsi_binzhou_order (`appid`, `tradeNo`, `readstate`,`state`, `price`, `pharCertNo`, `pharName`, " +
                                                "`tradeType`, `tradeStatus`, `tradeTime`, `name`, `socialCardNo`, `idCardNo`, `insuredCode`, `settleId`, `mdtrtId`, " +
                                                "`hiRxno`, `rxChkBizSn`, `hiFeesetlFlag`, `psnCashPay`, `mdtrtareaNo`, " +
                                                "`create_time`, `update_time`) VALUES " +
                                                "( @appid, @tradeNo,@readstate,@state,@price,@pharCertNo,@pharName," +
                                                "@tradeType,@tradeStatus,@tradeTime,@name,@socialCardNo,@idCardNo,@insuredCode,@settleId,@mdtrtId," +
                                                "@hiRxno,@rxChkBizSn,@hiFeesetlFlag,@psnCashPay,@mdtrtareaNo," +
                                                "@create_time,@update_time)";
                                            cmd.Parameters.AddWithValue("@appid", appid);
                                            cmd.Parameters.AddWithValue("@tradeNo", order.tradeNo);
                                            cmd.Parameters.AddWithValue("@readstate", 0);
                                            cmd.Parameters.AddWithValue("@state", 0);
                                            cmd.Parameters.AddWithValue("@price", order.price / 100);
                                            cmd.Parameters.AddWithValue("@pharCertNo", order.pharCertNo);
                                            cmd.Parameters.AddWithValue("@pharName", order.pharName);

                                            cmd.Parameters.AddWithValue("@tradeType", 2);
                                            cmd.Parameters.AddWithValue("@tradeStatus", 3);
                                            cmd.Parameters.AddWithValue("@tradeTime", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                            cmd.Parameters.AddWithValue("@name", psn_name);
                                            cmd.Parameters.AddWithValue("@socialCardNo", "D235131345");
                                            cmd.Parameters.AddWithValue("@idCardNo", cert_no);
                                            cmd.Parameters.AddWithValue("@insuredCode", "330211");
                                            cmd.Parameters.AddWithValue("@settleId", $"370000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}");
                                            cmd.Parameters.AddWithValue("@mdtrtId", dtunix);

                                            cmd.Parameters.AddWithValue("@hiRxno", "");
                                            cmd.Parameters.AddWithValue("@rxChkBizSn", "");
                                            cmd.Parameters.AddWithValue("@hiFeesetlFlag", "");
                                            cmd.Parameters.AddWithValue("@psnCashPay", 0);
                                            cmd.Parameters.AddWithValue("@mdtrtareaNo", "370000");

                                            cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                            cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                            await cmd.ExecuteNonQueryAsync();
                                            cmd.Parameters.Clear();
                                        }
                                        catch (Exception ex)
                                        {
                                            flag = 2;
                                            throw new Exception($"订单汇总数据异常：{ex.Message}");
                                        }
                                        string error = "";//商品错误循环拼接
                                        foreach (var item in list)
                                        {
                                            try
                                            {
                                                if (item.price* item.amount-item.amt>=1 || item.price * item.amount - item.amt <= -1)
                                                {
                                                    throw new Exception($"商品单价:{ Convert.ToDecimal(item.price)/100} 数量:{item.amount} 与商品合计金额:{Convert.ToDecimal(item.amt)/100}误差超过0.01");
                                                }
                                                cmd.CommandText = "INSERT INTO fsi_binzhou_order_detail (`tradeNo`, `typeCatalogue`, `name`, `price`, `amount`, `barCode`, `drugType`, `hilistCode`, `hilistName`, `fixmedinsHilistId`, `fixmedinsHilistName`, `drugstdCode`, `typeOP`, `prcunt`, `outRecipe`, `spec`, `dosform`, `amt`, `prdr`, `aprvNo`, `hilistType`, `create_time`, `update_time`)   VALUES (@tradeNo, @typeCatalogue, @name,@price, " +
                                                    "@amount, @barCode, @drugType, @hilistCode, @hilistName,@fixmedinsHilistId, @fixmedinsHilistName," +
                                                    "@drugstdCode, @typeOP,@prcunt,@outRecipe,@spec,@dosform,@amt,@prdr,@aprvNo,@hilistType," +
                                                    " @create_time, @update_time)";
                                                cmd.Parameters.AddWithValue("@tradeNo", order.tradeNo);
                                                cmd.Parameters.AddWithValue("@typeCatalogue", item.typeCatalogue);
                                                cmd.Parameters.AddWithValue("@name", item.name);
                                                cmd.Parameters.AddWithValue("@price", item.price / 100);
                                                cmd.Parameters.AddWithValue("@amount", item.amount);
                                                cmd.Parameters.AddWithValue("@barCode", item.barCode);
                                                cmd.Parameters.AddWithValue("@drugType", item.drugType);
                                                cmd.Parameters.AddWithValue("@hilistCode", item.hilistCode);
                                                cmd.Parameters.AddWithValue("@hilistName", item.hilistName);
                                                cmd.Parameters.AddWithValue("@fixmedinsHilistId", item.fixmedinsHilistId);
                                                cmd.Parameters.AddWithValue("@fixmedinsHilistName", item.fixmedinsHilistName);
                                                cmd.Parameters.AddWithValue("@drugstdCode", item.drugstdCode);
                                                cmd.Parameters.AddWithValue("@typeOP", item.typeOP);
                                                cmd.Parameters.AddWithValue("@prcunt", item.prcunt);
                                                cmd.Parameters.AddWithValue("@outRecipe", item.outRecipe);
                                                cmd.Parameters.AddWithValue("@spec", item.spec);
                                                cmd.Parameters.AddWithValue("@dosform", item.dosform);
                                                cmd.Parameters.AddWithValue("@amt", item.amt / 100);
                                                cmd.Parameters.AddWithValue("@prdr", item.prdr);
                                                cmd.Parameters.AddWithValue("@aprvNo", item.aprvNo);
                                                cmd.Parameters.AddWithValue("@hilistType", item.hilistType);
                                                cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                                cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                                await cmd.ExecuteNonQueryAsync();
                                                cmd.Parameters.Clear();
                                            }
                                            catch (Exception ex)
                                            {
                                                error = error + $"商品订单明细预订单号tradeNo:{order.tradeNo}商品:{item.name}异常！订单处理失败：" + ex.Message + "|";
                                            }
                                            cmd.Parameters.Clear();
                                        }
                                        if (error != "")
                                        {
                                            transaction.Rollback();
                                            flag = 2;
                                            throw new Exception(error);

                                        }
                                        else
                                        {
                                            transaction.Commit();
                                            flag = 1;
                                            Dictionary<string, int> dict = new Dictionary<string, int> { { "flag", flag } };
                                            returninfo = JsonConvert.SerializeObject(dict).ToString();
                                            var FsiBinZhouRequest = new FsiBinZhouRequest
                                            {
                                                code = 0,
                                                msg = "成功",
                                                bizContent = returninfo
                                            };
                                            return Json(FsiBinZhouRequest);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                string Errnum = LogHelper.GetErrornumber();
                                Dictionary<string, int> dict = new Dictionary<string, int> { { "flag", flag } };
                                returninfo = JsonConvert.SerializeObject(dict).ToString();
                                var FsiBinZhouRequest = new FsiBinZhouRequest
                                {
                                    code = 1,
                                    msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                    bizContent = returninfo
                                };
                                return Json(FsiBinZhouRequest);
                            }
                        //查询订单状态
                        case "query.social.trade.status":
                            var order1 = JsonConvert.DeserializeObject<BinzhouOrderQuery>(bizContent);
                            try
                            {
                                await conn.OpenAsync();
                                using (MySqlTransaction transaction = conn.BeginTransaction())
                                {
                                    using (MySqlCommand cmd = conn.CreateCommand())
                                    {

                                        cmd.CommandText = "select * from fsi_binzhou_order where tradeNo=@tradeNo and appid=@appid ";
                                        cmd.Parameters.AddWithValue("@tradeNo", order1.tradeNo);
                                        cmd.Parameters.AddWithValue("@appid", appid);
                                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                                        {
                                            DataTable dt = new DataTable();
                                            dt.Load(reader);
                                            cmd.Parameters.Clear();
                                            if (dt.Rows.Count != 1)
                                            {
                                                var OrderQuery = new outputBinzhouOrderQuery
                                                {
                                                    flag = 2,
                                                    tradeNo = order1.tradeNo,
                                                };
                                                returninfo = JsonConvert.SerializeObject(OrderQuery).ToString();
                                                throw new Exception($"查询订单表数据失败：传入的预订单编号tradeNo:{order1.tradeNo}和Appid:{appid}不存在或存在多条记录！查询到的记录数为：{dt.Rows.Count}");
                                            }
                                            else
                                            {
                                                cmd.Transaction = transaction;
                                                try
                                                {
                                                    cmd.CommandText = "update fsi_binzhou_order set readstate= @readstate,update_time = @update_time where tradeNo = @tradeNo";
                                                    cmd.Parameters.AddWithValue("@readstate", 1);
                                                    cmd.Parameters.AddWithValue("@tradeNo", order1.tradeNo);
                                                    cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                                    await cmd.ExecuteNonQueryAsync();
                                                    cmd.Parameters.Clear();
                                                }
                                                catch (Exception ex)
                                                {
                                                    transaction.Rollback();
                                                    var OrderQuery = new outputBinzhouOrderQuery
                                                    {
                                                        flag = 2,
                                                        tradeNo = order1.tradeNo,
                                                    };
                                                    returninfo = JsonConvert.SerializeObject(OrderQuery).ToString();
                                                    throw new Exception($"查询订单表数据失败：更新订单记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                                                }
                                                transaction.Commit();
                                                var OrderQuery2 = new outputBinzhouOrderQuery
                                                {
                                                    flag = 2,
                                                    tradeNo = order1.tradeNo,
                                                    tradeType = (int)dt.Rows[0]["tradeType"],
                                                    tradeStatus = (int)dt.Rows[0]["tradeStatus"],
                                                    tradeTime = dt.Rows[0]["tradeTime"].ToString(),
                                                    name = dt.Rows[0]["name"].ToString(),
                                                    socialCardNo = dt.Rows[0]["socialCardNo"].ToString(),
                                                    idCardNo = dt.Rows[0]["idCardNo"].ToString(),
                                                    insuredCode = dt.Rows[0]["insuredCode"].ToString(),
                                                    settleId = dt.Rows[0]["settleId"].ToString(),
                                                    mdtrtId = dt.Rows[0]["mdtrtId"].ToString(),
                                                    hiRxno = dt.Rows[0]["hiRxno"].ToString(),
                                                    rxChkBizSn = dt.Rows[0]["rxChkBizSn"].ToString(),
                                                    hiFeesetlFlag = dt.Rows[0]["hiFeesetlFlag"].ToString(),
                                                    psnCashPay = dt.Rows[0]["psnCashPay"].ToString(),
                                                    mdtrtareaNo = dt.Rows[0]["mdtrtareaNo"].ToString(),
                                                };
                                                returninfo = JsonConvert.SerializeObject(OrderQuery2).ToString();
                                                var FsiBinZhouRequest = new FsiBinZhouRequest
                                                {
                                                    code = 0,
                                                    msg = "成功",
                                                    bizContent = returninfo
                                                };
                                                return Json(FsiBinZhouRequest);
                                            }
                                        }
                                    }
                                }

                            }
                            catch (Exception ex)
                            {
                                string Errnum = LogHelper.GetErrornumber();
                                var FsiBinZhouRequest = new FsiBinZhouRequest
                                {
                                    code = 1,
                                    msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                    bizContent = returninfo
                                };
                                return Json(FsiBinZhouRequest);
                            }
                        //订单退款
                        case "submit.social.trade.refund":
                            int flag2 = 2; //查询标志
                            try
                            {
                                var order2 = JsonConvert.DeserializeObject<BinzhouOrderReturn>(bizContent);
                                await conn.OpenAsync();
                                using (MySqlTransaction transaction = conn.BeginTransaction())
                                {
                                    using (MySqlCommand cmd = conn.CreateCommand())
                                    {
                                        cmd.CommandText = "select * from fsi_binzhou_order where tradeNo=@tradeNo and appid=@appid and state = 0";
                                        cmd.Parameters.AddWithValue("@tradeNo", order2.tradeNo);
                                        cmd.Parameters.AddWithValue("@appid", appid);
                                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                                        {
                                            DataTable dt = new DataTable();
                                            dt.Load(reader);
                                            cmd.Parameters.Clear();
                                            if (dt.Rows.Count != 1)
                                            {
                                                flag2 = 3;
                                                throw new Exception($"撤销订单失败：传入的尚未退款的预订单编号tradeNo:{order2.tradeNo}和Appid:{appid}不存在或存在多条记录！查询到的记录数为：{dt.Rows.Count}");
                                            }
                                            else
                                            {
                                                cmd.Transaction = transaction;
                                                try
                                                {
                                                    cmd.CommandText = "update fsi_binzhou_order set state= @state,update_time = @update_time,tradeNoReturn = @tradeNoReturn where tradeNo = @tradeNo";
                                                    cmd.Parameters.AddWithValue("@state", order2.refundType);
                                                    cmd.Parameters.AddWithValue("@tradeNoReturn", order2.refundNo);
                                                    cmd.Parameters.AddWithValue("@tradeNo", order2.tradeNo);
                                                    cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                                    await cmd.ExecuteNonQueryAsync();
                                                    cmd.Parameters.Clear();
                                                }
                                                catch (Exception ex)
                                                {
                                                    transaction.Rollback();
                                                    flag2 = 2;
                                                    throw new Exception($"撤销订单失败：更新订单记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                                                }
                                                transaction.Commit();
                                                flag = 0;
                                                Dictionary<string, int> dict = new Dictionary<string, int> { { "flag", flag } };
                                                returninfo = JsonConvert.SerializeObject(dict).ToString();
                                                var FsiBinZhouRequest = new FsiBinZhouRequest
                                                {
                                                    code = 0,
                                                    msg = "成功",
                                                    bizContent = returninfo
                                                };
                                                return Json(FsiBinZhouRequest);
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                string Errnum = LogHelper.GetErrornumber();
                                Dictionary<string, int> dict = new Dictionary<string, int> { { "flag", flag2 } };
                                returninfo = JsonConvert.SerializeObject(dict).ToString();
                                var FsiBinZhouRequest = new FsiBinZhouRequest
                                {
                                    code = 1,
                                    msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                    bizContent = returninfo
                                };
                                return Json(FsiBinZhouRequest);
                            }
                        //数据上传
                        case "update.store.catalogue":
                            try
                            {
                                var catalogue = JsonConvert.DeserializeObject<Binzhoucatalogue>(bizContent);
                                await conn.OpenAsync();
                                using (MySqlCommand cmd = conn.CreateCommand())
                                {
                                    cmd.CommandText = "INSERT INTO `fsi_binzhou_catalogue` ( `appid`,`p_yyxmbm`, `p_yyxmmc`, " +
                                        "`p_ypbz`, `p_dj`, `p_zxgg`, `p_bhsl`, `p_zdgg`, `p_mzjsxmbh`, `p_zyjsxmbh`, `p_jj`, `p_scqy`, " +
                                        "`p_spm`, `p_dw`, `p_gmpbz`, `p_cfybz`, `p_jxm`, `p_ylxmbm`, `p_bcxm`, `p_syz`, `p_pjcpmc`, `p_zczh`, " +
                                        "`p_zcjzrq`, `p_cdm`, `p_model`, `p_cljj`, `update_time`, `create_time`) values" +
                                        "(@appid,@p_yyxmbm,@p_yyxmmc,@p_ypbz,@p_dj,@p_zxgg,@p_bhsl,@p_zdgg,@p_mzjsxmbh,@p_zyjsxmbh,@p_jj,@p_scqy," +
                                        "@p_spm,@p_dw,@p_gmpbz,@p_cfybz,@p_jxm,@p_ylxmbm,@p_bcxm,@p_syz,@p_pjcpmc,@p_zczh," +
                                        "@p_zcjzrq,@p_cdm,@p_model,@p_cljj,@update_time,@create_time)";
                                    cmd.Parameters.AddWithValue("@appid", appid);
                                    cmd.Parameters.AddWithValue("@p_yyxmbm", catalogue.p_yyxmbm);
                                    cmd.Parameters.AddWithValue("@p_yyxmmc", catalogue.p_yyxmmc);
                                    cmd.Parameters.AddWithValue("@p_ypbz", catalogue.p_ypbz);
                                    cmd.Parameters.AddWithValue("@p_dj", catalogue.p_dj);
                                    cmd.Parameters.AddWithValue("@p_zxgg", catalogue.p_zxgg);
                                    cmd.Parameters.AddWithValue("@p_bhsl", catalogue.p_bhsl);
                                    cmd.Parameters.AddWithValue("@p_zdgg", catalogue.p_zdgg);
                                    cmd.Parameters.AddWithValue("@p_mzjsxmbh", catalogue.p_mzjsxmbh);
                                    cmd.Parameters.AddWithValue("@p_zyjsxmbh", catalogue.p_zyjsxmbh);
                                    cmd.Parameters.AddWithValue("@p_jj", catalogue.p_jj);
                                    cmd.Parameters.AddWithValue("@p_scqy", catalogue.p_scqy);
                                    cmd.Parameters.AddWithValue("@p_spm", catalogue.p_spm);
                                    cmd.Parameters.AddWithValue("@p_dw", catalogue.p_dw);
                                    cmd.Parameters.AddWithValue("@p_gmpbz", catalogue.p_gmpbz);
                                    cmd.Parameters.AddWithValue("@p_cfybz", catalogue.p_cfybz);
                                    cmd.Parameters.AddWithValue("@p_jxm", catalogue.p_jxm);
                                    cmd.Parameters.AddWithValue("@p_ylxmbm", catalogue.p_ylxmbm);
                                    cmd.Parameters.AddWithValue("@p_bcxm", catalogue.p_bcxm);
                                    cmd.Parameters.AddWithValue("@p_syz", catalogue.p_syz);
                                    cmd.Parameters.AddWithValue("@p_pjcpmc", catalogue.p_pjcpmc);
                                    cmd.Parameters.AddWithValue("@p_zczh", catalogue.p_zczh);
                                    cmd.Parameters.AddWithValue("@p_zcjzrq", catalogue.p_zcjzrq);
                                    cmd.Parameters.AddWithValue("@p_cdm", catalogue.p_cdm);
                                    cmd.Parameters.AddWithValue("@p_model", catalogue.p_model);
                                    cmd.Parameters.AddWithValue("@p_cljj", catalogue.p_cljj);
                                    cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                    cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                    await cmd.ExecuteNonQueryAsync();

                                    var outputcatalogue = new outputBinzhoucatalogue
                                    {
                                        resultcode = 0
                                    };
                                    returninfo = JsonConvert.SerializeObject(outputcatalogue).ToString();

                                    var FsiBinZhouRequest = new FsiBinZhouRequest
                                    {
                                        code = 0,
                                        msg = "成功",
                                        bizContent = returninfo
                                    };
                                    return Json(FsiBinZhouRequest);
                                }
                            }
                            catch (Exception ex)
                            {
                                var outputcatalogue = new outputBinzhoucatalogue
                                {
                                    resultcode = -2,
                                    resulttext = ex.Message,
                                };
                                returninfo = JsonConvert.SerializeObject(outputcatalogue).ToString();

                                var FsiBinZhouRequest = new FsiBinZhouRequest
                                {
                                    code = 0,
                                    msg = "成功",
                                    bizContent = returninfo
                                };
                                return Json(FsiBinZhouRequest);
                            }
                        //处方列表
                        case "query.epc.list":
                            try
                            {

                                int pagetotal = 0;//数据总条数
                                string prscTime_start = "";//开方开始时间
                                string prscTime_end = "";//开方结束时间
                                string patn_name = "";//患者姓名
                                var epcinput = JsonConvert.DeserializeObject<BinzhouQueryEpc>(bizContent);
                                if (epcinput.pageNo <= 0 || epcinput.pageSize <=0)
                                {
                                    throw new Exception("处方入参参数校验失败!pageno页数或pagesize每页条数参数<=0或参数丢失!请检查入参参数是否正常!");
                                }
                                if (string.IsNullOrEmpty(epcinput.prscTime_ge))
                                {
                                    prscTime_start = dateTime.ToString("yyyy-MM-dd")+" 00:00:00";
                                }
                                else
                                {
                                    prscTime_start = epcinput.prscTime_ge;
                                }
                                if (string.IsNullOrEmpty(epcinput.prscTime_le))
                                {
                                    prscTime_end = dateTime.ToString("yyyy-MM-dd") + " 23:59:59";
                                }
                                else
                                {
                                    prscTime_end = epcinput.prscTime_le;
                                }
                                patn_name=epcinput.patnName;
     
                                int pageno = epcinput.pageNo;//当前页
                                int pageSize = epcinput.pageSize;//本页数据
                                int now_page = (pageno - 1) * pageSize;//计算数据
                                await conn.OpenAsync();
                                DataTable dtEpcInfo = new DataTable();
                                DataTable dtEpcdrugInfo = new DataTable();
                                List<outputBinzhouEpcList> dataList = new List<outputBinzhouEpcList>();
                                List<outputBinzhouEpcdrugList> datadrugList = new List<outputBinzhouEpcdrugList>();
                                using (MySqlTransaction transaction = conn.BeginTransaction())
                                {
                                    using (MySqlCommand cmdcount = conn.CreateCommand())
                                    {
                                        cmdcount.CommandText = "select * from fsi_prescription where prsc_time >=@prscTime_start and prsc_time <=@prscTime_end and patn_name like @patn_name ";
                                        cmdcount.Parameters.AddWithValue("@patn_name", "%" + patn_name + "%");
                                        cmdcount.Parameters.AddWithValue("@prscTime_start", prscTime_start);
                                        cmdcount.Parameters.AddWithValue("@prscTime_end", prscTime_end);
                                        using (MySqlDataReader reader = (MySqlDataReader)await cmdcount.ExecuteReaderAsync())
                                        {
                                            DataTable dt = new DataTable();
                                            dt.Load(reader);
                                            pagetotal = dt.Rows.Count;
                                            cmdcount.Parameters.Clear();
                                        }
                                    }
                                    using (MySqlCommand cmd = conn.CreateCommand())
                                    {
                                        cmd.CommandText = "select * from fsi_prescription where prsc_time >=@prscTime_start and prsc_time <=@prscTime_end and patn_name like @patn_name limit @nowpage,@pagesize";
                                        cmd.Parameters.AddWithValue("@patn_name", "%" + patn_name + "%");
                                        cmd.Parameters.AddWithValue("@prscTime_start", prscTime_start);
                                        cmd.Parameters.AddWithValue("@prscTime_end", prscTime_end);
                                        cmd.Parameters.AddWithValue("@nowpage", now_page);
                                        cmd.Parameters.AddWithValue("@pagesize", pageSize);
                                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                                        {
                                            dtEpcInfo.Load(reader);
                                            cmd.Parameters.Clear();
                                            if (dtEpcInfo.Rows.Count != 0)
                                            {
                                                foreach (DataRow row in dtEpcInfo.Rows)
                                                {
                                                    using (MySqlCommand cmd2 = conn.CreateCommand())
                                                    {
                                                        cmd2.CommandText = "select * from fsi_prescription_detail where  auth_rxno=@auth_rxno";
                                                        cmd2.Parameters.AddWithValue("@auth_rxno", row["auth_rxno"].ToString());
                                                        using (MySqlDataReader reader2 = (MySqlDataReader)await cmd2.ExecuteReaderAsync())
                                                        {
                                                            dtEpcdrugInfo.Load(reader2);
                                                            cmd2.Parameters.Clear();
                                                            if (dtEpcdrugInfo.Rows.Count != 0)
                                                            {
                                                                foreach (DataRow row2 in dtEpcdrugInfo.Rows)
                                                                {
                                                                    datadrugList.Clear();
                                                                    outputBinzhouEpcdrugList item2 = new outputBinzhouEpcdrugList
                                                                    {
                                                                        medListCodg = row2["med_list_codg"].ToString(),
                                                                        fixmedinsHilistId = row2["fixmedins_hilist_id"].ToString(),
                                                                        hospPrepFlag = row2["hosp_prep_flag"].ToString(),
                                                                        rxItemTypeCode = row2["rx_item_type_code"].ToString(),
                                                                        rxItemTypeName = row2["rx_item_type_name"].ToString(),
                                                                        tcmdrugTypeCode = row2["tcmdrug_type_code"].ToString(),
                                                                        tcmdrugTypeName = row2["tcmdrug_type_name"].ToString(),
                                                                        tcmherbFoote = row2["tcmherb_foote"].ToString(),
                                                                        mednTypeCode = row2["medn_type_code"].ToString(),
                                                                        mednTypeName = row2["medn_type_name"].ToString(),
                                                                        mainMedcFlag = row2["main_medc_flag"].ToString(),
                                                                        urgtFlag = row2["urgt_flag"].ToString(),
                                                                        basMednFlag = row2["bas_medn_flag"].ToString(),
                                                                        impDrugFlag = row2["imp_drug_flag"].ToString(),
                                                                        drugProdname = row2["drug_prodname"].ToString(),
                                                                        drugGenname = row2["drug_genname"].ToString(),
                                                                        drugDosform = row2["drug_dosform"].ToString(),
                                                                        drugSpec = row2["drug_spec"].ToString(),
                                                                        prdrName = row2["prdr_name"].ToString(),
                                                                        drugCnt = Convert.ToDouble(row2["drug_cnt"]),
                                                                        medcWayCodg = row2["medc_way_codg"].ToString(),
                                                                        medcWayDscr = row2["medc_way_dscr"].ToString(),
                                                                        medcDays = Convert.ToDouble(row2["medc_days"]),
                                                                        drugDosunt = row2["drug_dosunt"].ToString(),
                                                                        sinDoscnt = Convert.ToDouble(row2["sin_doscnt"]),
                                                                        sinDosunt = row2["sin_dosunt"].ToString(),
                                                                        usedFrquCodg = row2["used_frqu_codg"].ToString(),
                                                                        usedFrquName = row2["used_frqu_name"].ToString(),
                                                                        drugTotlcnt = Convert.ToDouble(row2["drug_totlcnt"]),
                                                                        drugTotlcntEmp = row2["drug_totlnt_emp"].ToString(),
                                                                        hospApprFlag = row2["hosp_appr_flag"].ToString()
                                                                    };
                                                                    datadrugList.Add(item2);
                                                                }
                                                            }
                                                        };
                                                    }
                                                    outputBinzhouEpcList item = new outputBinzhouEpcList
                                                    {
                                                        id = row["auth_rxno"].ToString(),
                                                        hiRxno = row["hi_rxno"].ToString(),
                                                        rxTraceCode = row["epc_token"].ToString(),
                                                        fixmedinsCode = row["fixmedins_code"].ToString(),
                                                        fixmedinsName = row["fixmedins_name"].ToString(),
                                                        prscTime = row["prsc_time"].ToString(),
                                                        prscDeptName = row["prsc_dept_name"].ToString(),
                                                        valiEndTime = row["valid_end_time"].ToString(),
                                                        rxTypeCode = row["rx_type_code"].ToString(),
                                                        rxTypeName = row["rx_type_name"].ToString(),
                                                        longRxFlag = row["long_rx_flag"].ToString(),
                                                        rxFileId = /*row["rx_file"].ToString()*/"",
                                                        fileSuffix = row["file_suffix"].ToString(),
                                                        medType = row["med_type"].ToString(),
                                                        otpIptFlag = row["otp_ipt_flag"].ToString(),
                                                        patnName = row["patn_name"].ToString(),
                                                        //patnAge = Convert.ToDouble(row["patn_age"]),
                                                        //patnHgt = Convert.ToDouble(row["patn_hgt"]),
                                                       //patnWt = Convert.ToDouble(row["patn_wt"]),
                                                        gend = row["gend"].ToString(),
                                                        nwbFlag = row["nwb_flag"].ToString(),
                                                        nwbAge = row["nwb_age"].ToString(),
                                                        suckPrdFlag = row["suck_prd_flag"].ToString(),
                                                        algsHis = row["algs_his"].ToString(),
                                                        maindiagCode = row["main_diag_code"].ToString(),
                                                        maindiagName = row["main_diag_name"].ToString(),
                                                        diseCondDscr = row["dise_cond_dscr"].ToString(),
                                                        diseCodg = row["dise_codg"].ToString(),
                                                        diseName = row["dise_name"].ToString(),
                                                        drugList = datadrugList
                                                    };
                                                    dataList.Add(item);
                                                }
                                            }
                                            else
                                            {
                                                dataList = null;
                                            }
                                            var EpcList = new outputBinzhouQueryEpc
                                            {
                                                flag = 0,
                                                total = pagetotal,
                                                epcList = dataList
                                            };
                                            returninfo = JsonConvert.SerializeObject(EpcList).ToString();
                                            var FsiBinZhouRequest = new FsiBinZhouRequest
                                            {
                                                code = 0,
                                                msg = "成功",
                                                bizContent = returninfo
                                            };
                                            return Json(FsiBinZhouRequest);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                string Errnum = LogHelper.GetErrornumber();
                                var FsiBinZhouRequest = new FsiBinZhouRequest
                                {
                                    code = 1,
                                    msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                    bizContent = returninfo
                                };
                                return Json(FsiBinZhouRequest);
                            }
                        default:
                            throw new Exception($"[滨州医保]接口{mothod}未被定义，请检查入参或联系管理员！");
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiBinZhouRequest = new FsiBinZhouRequest
                    {
                        code = 1,
                        bizContent = "",
                        msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                    };
                    return Json(FsiBinZhouRequest);
                }
            }
        }
    }
}
